<?php

declare(strict_types=1);

namespace app\common\dao\crm;

use app\common\model\crm\CrmContract;
use app\common\traits\DaoTrait;

/**
 * 合同表 数据访问层(Dao)
 * @author 吕玉冰
 * @date  2022-07-23
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class ContractDao
{
    // 当前操作的模型
    protected $model = null;

    // 对应模型的主键，默认为id
    protected $pk = 'id';

    // 对应模型默认查询的字段
    protected $name = '';

    // 对应模型允许查询的字段(默认全部查询)
    protected $allowField = ['*'];

    // 允许单字段更新
    protected $uaField = [''];

    // 查询结果-要隐藏的字段 默认空数组
    protected $hideField = [];

    public function __construct()
    {
        $this->model = new CrmContract();
    }

    use DaoTrait;

    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return mixed
     */
    public function update($id, $data)
    {
        $result = $this->model->find($id);
        if ($result) {
            return $result->allowField(['name', 'money', 'start_time', 'end_time'])->save($data);
        } else {
            return false;
        }
    }

    public function getAddNumberByWeek($user_ids)
    {
        $where = [];
        $where[] = ['owner_user_id', 'in', $user_ids];
        $start = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
        $end = date('Y-m-d', (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600));
        return $this->model->where($where)->whereBetweenTime('order_date', $start, $end)->count();
    }

    public function getMoneyByGroupMonth($user_ids)
    {
        $where = [];
        $where[] = ['owner_user_id', 'in', $user_ids];
        $month = date("Y-m");
        $end = date("Y-m-d", strtotime("+1 month -1 day", strtotime($month)));
        $start = date("Y-m-d", strtotime("-1 year", strtotime($month)));
        $data = $this->model->field("sum(money) as money,DATE_FORMAT(order_date,'%Y-%m') as month")->where($where)->whereBetweenTime('order_date', $start, $end)->group("month")->select()->toArray();
        $re = [];
        foreach ($data as $k => $v) {
            $re[$v['month']] = $v["money"];
        }
        return $re;
    }

    public function getTotalByGroupMonth($user_ids)
    {
        $where = [];
        $where[] = ['owner_user_id', 'in', $user_ids];
        $month = date("Y-m");
        $end = date("Y-m-d", strtotime("+1 month -1 day", strtotime($month)));
        $start = date("Y-m-d", strtotime("-1 year", strtotime($month)));
        $data = $this->model->field("count(money) as c,DATE_FORMAT(order_date,'%Y-%m') as month")->where($where)->whereBetweenTime('order_date', $start, $end)->group("month")->select()->toArray();
        $re = [];
        foreach ($data as $k => $v) {
            $re[$v['month']] = $v["c"];
        }
        return $re;
    }


}